package com.chenjl.transaction.service.impl;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.chenjl.transaction.dto.MessageQueueBody;
import com.chenjl.transaction.service.MessageQueueService;

import lombok.extern.slf4j.Slf4j;
/**
 * RabbitMQ监听特定的queue
 * 2019-9-11 15:19:43
 * @author chenjinlong
 */
@Slf4j
@Service("rabbitMQMessageListener")
public class RabbitMQMessageListener implements MessageListener {	
	
	@Autowired
	private MessageQueueService messageQueueService;
	
	
	
	@Override
	public void onMessage(Message message) {
		String consumerQueue = message.getMessageProperties().getConsumerQueue();
		String messageBodyStr = new String(message.getBody());
		log.info("RabbitMQ收到消息待处理...messageBodyStr:{},consumerQueue:{}",messageBodyStr,consumerQueue);
		
		//Integer.parseInt("1D");
		MessageQueueBody messageQueueBody = JSONObject.parseObject(messageBodyStr,MessageQueueBody.class);
		
		//检查消息重复与业务在一个Transaction中
		//Transaction begin
		boolean canConsumeFlag = messageQueueService.canQueueConsume(messageQueueBody,consumerQueue);
		log.info("RabbitMQ收到消息检查是否重复消息...messageBodyStr:{},consumerQueue:{},canConsumeFlag:{}",messageBodyStr,consumerQueue,canConsumeFlag);
		if(canConsumeFlag) {
			//业务正常消费消息，不要catch任何异常
			//do Biz
			log.info("RabbitMQ收到消息处理完成....messageBodyStr:{},consumerQueue:{}",messageQueueBody,consumerQueue);
		}
		//Transaction end
	}
}